<template>
  <div class="app-container">
 <!-- 搜索条件 -->
<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
  <el-row :gutter="20">
    <!-- 第一行 -->
    <el-col :span="24">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="编码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="风险类别" prop="riskCategory">
        <el-select v-model="queryParams.riskCategory" placeholder="请选择风险类别" clearable>
          <el-option label="设备设施" value="设备设施" />
          <el-option label="作业类型" value="作业类型" />
        </el-select>
      </el-form-item>
    </el-col>
    
   <!-- 第二行 -->
   <el-col :span="24">
      <el-form-item label="发生场所" prop="occurrencePlace">
        <el-input
          v-model="queryParams.occurrencePlace"
          placeholder="请输入发生场所"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="责任部门" prop="responsibleDepartment">
        <el-input
          v-model="queryParams.responsibleDepartment"
          placeholder="请输入责任部门"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="责任人" prop="responsiblePerson">
        <el-input
          v-model="queryParams.responsiblePerson"
          placeholder="请输入责任人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
    </el-col>
  </el-row>
  
  <el-form-item>
    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
    <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
  </el-form-item>
</el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
     <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table v-loading="loading" :data="emergencyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="编码" align="center" prop="code" />
      <el-table-column label="责任人" align="center" prop="responsiblePerson" />
      <el-table-column label="联系方式" align="center" prop="contactOfResponsible" />
      <el-table-column label="责任部门" align="center" prop="responsibleDepartment" />
      <el-table-column label="岗位" align="center" prop="position" />
      <el-table-column label="风险类别" align="center" prop="riskCategory" />
      <el-table-column label="风险点" align="center" prop="riskPoint" />
      <el-table-column label="风险区域" align="center" prop="riskArea" />
      <el-table-column label="发生场所" align="center" prop="occurrencePlace" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
              <el-button
        size="mini"
        type="text"
        icon="el-icon-view"
        @click="handleView(scope.row)"
      >查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改应急处理卡对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="720px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入名称" />
            </el-form-item>
            <el-form-item label="编码" prop="code">
              <el-input v-model="form.code" placeholder="请输入编码" />
            </el-form-item>
            <el-form-item label="责任人" prop="responsiblePerson">
              <el-input v-model="form.responsiblePerson" placeholder="请输入责任人" />
            </el-form-item>
            <el-form-item label="联系方式" prop="contactOfResponsible">
              <el-input v-model="form.contactOfResponsible" placeholder="请输入联系方式" />
            </el-form-item>
            <el-form-item label="责任部门" prop="responsibleDepartment">
              <el-input v-model="form.responsibleDepartment" placeholder="请输入责任部门" />
            </el-form-item>
            <el-form-item label="岗位" prop="position">
              <el-input v-model="form.position" placeholder="请输入岗位" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="风险类别" prop="riskCategory">
              <el-select v-model="form.riskCategory" placeholder="请选择风险类别">
                <el-option label="设备设施" value="设备设施" />
                <el-option label="作业类型" value="作业类型" />
              </el-select>
            </el-form-item>
            <el-form-item label="风险点" prop="riskPoint">
              <el-input v-model="form.riskPoint" placeholder="请输入风险点" />
            </el-form-item>
            <el-form-item label="风险区域" prop="riskArea">
              <el-input v-model="form.riskArea" placeholder="请输入风险区域" />
            </el-form-item>
            <el-form-item label="上报时限" prop="reportingDeadline">
              <el-date-picker v-model="form.reportingDeadline" type="datetime" placeholder="请选择时间" style="width: 100%;"></el-date-picker>
            </el-form-item>
            <el-form-item label="发生场所" prop="occurrencePlace">
              <el-input v-model="form.occurrencePlace" placeholder="请输入发生场所" />
            </el-form-item>
            <el-form-item label="工艺说明" prop="processDescription">
              <el-input type="textarea" :rows="3" v-model="form.processDescription" placeholder="请输入工艺说明" />
            </el-form-item>
            <el-form-item label="事故特征" prop="accidentCharacteristic">
              <el-input v-model="form.accidentCharacteristic" placeholder="请输入事故特征" />
            </el-form-item>
            <el-form-item label="危害描述" prop="hazardDescription">
              <el-input v-model="form.hazardDescription" placeholder="请输入危害描述" />
            </el-form-item>
            <el-form-item label="有害因素" prop="hazardousFactors">
              <el-input v-model="form.hazardousFactors" placeholder="请输入有害因素" />
            </el-form-item>
            <el-form-item label="处理措施" prop="treatmentMeasures">
              <el-input type="textarea" :rows="3" v-model="form.treatmentMeasures" placeholder="请输入处理措施" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listEmergency, getEmergency, delEmergency, addEmergency, updateEmergency } from "@/api/system/emergency";
import { getToken } from "@/utils/auth";

export default {
  name: "Emergency",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 应急处理卡表格数据
      emergencyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        riskCategory: null,
        occurrencePlace: null,
        code: null,
        responsibleDepartment: null,
        position: null,
        responsiblePerson: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        code: [
          { required: true, message: "编码不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    // 检查是否有token
    const token = this.$store.getters.token || getToken();
    if (!token) {
      this.$router.push('/login');
      return;
    }
    this.getList();
  },
  methods: {
    /** 查看按钮操作 */
handleView(row) {
  this.reset();
  const id = row.id;
  getEmergency(id).then(response => {
    this.form = response.data;
    this.open = true;
    this.title = "查看现场应急处理卡";
    // 禁用表单编辑
    this.$nextTick(() => {
      this.$refs["form"].clearValidate();
      const formElements = this.$refs["form"].$el.querySelectorAll("input, textarea, select");
      formElements.forEach(element => {
        element.disabled = true;
      });
      // 禁用下拉框
      const selectElements = this.$refs["form"].$el.querySelectorAll(".el-select input");
      selectElements.forEach(element => {
        element.disabled = true;
      });
      // 禁用日期选择器
      const datePickerElements = this.$refs["form"].$el.querySelectorAll(".el-date-editor input");
      datePickerElements.forEach(element => {
        element.disabled = true;
      });
    });
  }).catch(error => {
    console.error("获取应急处理卡详情失败:", error);
    this.$modal.msgError("获取详情失败，请稍后重试");
  });
},
    /** 查询应急处理卡列表 */
getList() {
  this.loading = true;
  listEmergency(this.queryParams).then(response => {
    console.log('后端返回的原始数据:', response); // 调试用
    
    // 根据实际后端返回格式进行处理
    if (response && typeof response === 'object') {
      // 如果返回的是Page对象格式
      if (response.records) {
        this.emergencyList = response.records.map(item => item || {});
        this.total = response.total || 0;
      } 
      // 如果直接返回数组
      else if (Array.isArray(response)) {
        this.emergencyList = response.map(item => item || {});
        this.total = response.length;
      }
      // 如果是其他格式，尝试直接使用
      else if (response.rows) {
        this.emergencyList = response.rows.map(item => item || {});
        this.total = response.total || 0;
      }
      else {
        this.emergencyList = [];
        this.total = 0;
      }
    } else {
      this.emergencyList = [];
      this.total = 0;
    }
    
    this.loading = false;
  }).catch(error => {
    console.error("获取应急处理卡列表失败:", error);
    this.emergencyList = [];
    this.total = 0;
    this.loading = false;
  });
},
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        code: null,
        responsiblePerson: null,
        contactOfResponsible: null,
        responsibleDepartment: null,
        position: null,
        riskCategory: null,
        riskPoint: null,
        riskArea: null,
        reportingDeadline: null,
        occurrencePlace: null,
        processDescription: null,
        accidentCharacteristic: null,
        hazardDescription: null,
        hazardousFactors: null,
        treatmentMeasures: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加现场应急处理卡";
    },
    /** 修改按钮操作 */
 handleUpdate(row) {
  this.reset();
  const id = row.id || this.ids;
  getEmergency(id).then(response => {
    this.form = response.data;
    this.open = true;
    this.title = "修改现场应急处理卡";
  }).catch(error => {
    console.error("获取应急处理卡详情失败:", error);
    this.$modal.msgError("获取详情失败，请稍后重试");
  });
},
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateEmergency(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addEmergency(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除应急处理卡编号为"' + ids + '"的数据项？').then(function() {
        return delEmergency(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
  handleExport() {
  this.download('emergency/emergency/export', {
        ...this.queryParams
      }, `test_${new Date().getTime()}.xlsx`)
}
  }
};
</script>